superstrict

framework BRL.Blitz
import BRL.StandardIO
import BRL.PolledInput
import Bah.RakNet

(new ServerTest).main();

type ServerPeer

	function create:ServerPeer(maxConnections:int, threadSleepTimer:short, port:short)
	
		local s:ServerPeer= new ServerPeer;
		
		s.m_peer = TRKRakNetworkFactory.GetRakPeerInterface();
		s.m_socketDescr = TRKSocketDescriptor.CreateSocketDescriptor(port);
		s.m_sysaddr = s.m_peer.GetInternalID(UNASSIGNED_SYSTEM_ADDRESS);
		s.m_port = port;
		
		s.m_peer.Startup(maxConnections, threadSleepTimer, s.m_socketDescr);
		s.m_peer.SetMaximumIncomingConnections(maxConnections);
		
		return s;
	
	end function
	
	method managePackets()
	
		local packet:TRKPacket = m_peer.Receive();
		
		if (packet)
		
			local data:string = string.FromCString(packet.GetData());
			local msgType:int = packet.GetPacketIdentifier();
			local senderAddr:TRKSystemAddress = packet.GetSystemAddress();
			local senderPort:string = senderAddr.GetPort();
			local senderIndex:int = m_peer.GetIndexFromSystemAddress(senderAddr);
			
			select (msgType)
			
				case ID_NEW_INCOMING_CONNECTION
					print("Client " + senderIndex + " connected from " + senderAddr.ToString() + ":" + senderPort + ".");
				case ID_DISCONNECTION_NOTIFICATION
					print("Client " + senderIndex + " disconnected.");
				case ID_CONNECTION_LOST
					print("Client " + senderIndex + " timed out.");
				case ID_MODIFIED_PACKET
					print("WARNING: Received modified packet from " + senderAddr.ToString() + ":" + senderPort + "!");
					m_peer.CloseConnection(senderAddr, 1);
					print("Connection kicked.");
				default
					print("Unknown packet received from " + senderAddr.ToString() + ":" + senderPort + ..
						" containing the data ~q" + data + "~q.");
			
			end select
		
		end if
	
	end method
	
	method destroy()
	
		m_peer.Shutdown(300);
		TRKRakNetworkFactory.DestroyRakPeerInterface(m_peer);
	
	end method
	
	field m_peer:TRKRakPeerInterface;
	field m_socketDescr:TRKSocketDescriptor;
	field m_sysaddr:TRKSystemAddress;
	field m_port:short;

end type

type ServerTest

	method main()
	
		local server_peer:ServerPeer = ServerPeer.create(32, 30, 27530);
		
		print("Server started successfully.");
		
		while (true)
		
			delay(10);
			server_peer.managePackets();
		
		end while
		
		server_peer.destroy();
	
	end method

end type

